package com.tjl.controller;

import com.tjl.model.Type;
import com.tjl.service.Impl.TypeServiceImpl;
import com.tjl.util.CodeMsg;
import com.tjl.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author TJL
 * @date 2022/5/26
 */
@RestController
@RequestMapping("/types")
public class TypeController {

    @Autowired
    private TypeServiceImpl typeService;

    @Autowired
    private JwtUtils jwtUtils;

    @GetMapping
    public CodeMsg getAll(){
        return new CodeMsg(typeService.list());
    }

    @GetMapping("/{id}")
    public CodeMsg getOne(@PathVariable Integer id){
        return new CodeMsg(typeService.getById(id));
    }

    @PutMapping
    public CodeMsg update(@RequestHeader String token,@RequestBody Type type){
        Claims claims;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }
        return new CodeMsg(typeService.updateById(type));
    }

    @PostMapping
    public CodeMsg add(@RequestHeader String token,@RequestBody Type type){
        Claims claims;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }
        return new CodeMsg(typeService.save(type));
    }

    @DeleteMapping("/{id}")
    public CodeMsg delete(@PathVariable Integer id,@RequestHeader String token){
        Claims claims;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            return new CodeMsg(202,"token异常");
        }
        return new CodeMsg(typeService.removeById(id));
    }
}
